package com.hd.trans.ui.activity;


import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.common.Constants;
import com.hd.trans.db.DataBaseMgr;
import com.hd.trans.db.bean.HuDunLanguage;
import com.hd.trans.db.bean.TranslateRecord;
import com.hd.trans.framework.click.SingleItemClick;
import com.hd.trans.framework.click.XClickUtil;
import com.hd.trans.framework.dialog.LanguageDialog;
import com.hd.trans.framework.dialog.LanguageDialogType;
import com.hd.trans.framework.dialog.ShareDialog;
import com.hd.trans.framework.languages.ShareItemBean;
import com.hd.trans.framework.languages.ShareResultAdapter;
import com.hd.trans.homefun.EventCode;
import com.hd.trans.limit4Use.LimitUseListener;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.network.component.HdTranslateComponent2;
import com.hd.trans.network.component.TranslateCallback;
import com.hd.trans.share.EnShareFileType;
import com.hd.trans.share.ShareTextFileManager;
import com.hd.trans.ui.adapter.RecordTextAdapter;
import com.hd.trans.ui.base.LimitBaseActivity;
import com.hd.trans.ui.model.HomeTextModel;
import com.hd.trans.utils.StringUtils;
import com.hd.trans.utils.ToastUtils;
import com.hd.trans.utils.TrackerForTrans;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * 文本翻译
 */
public class TextHomeActivity extends LimitBaseActivity {


    @Override
    protected int getLayoutId() {
        return R.layout.activity_text_home;
    }

    private ImageView back;
    private TextView fromText;
    private TextView toText;
    private ImageView exchange;
    private EditText edit;
    private TextView clear;
    private TextView begin;
    private LinearLayout historyLayout;
    private LinearLayout moreLayout;
    private TextView moreText;
    private ImageView moerIcon;
    private ImageView imgShare;
    private RecyclerView historyRecycler;
    private RelativeLayout contentLayout;
    private RelativeLayout translateLayout;
    private TextView tvTranslated;
    private LinearLayout copyLayout;
    private LinearLayout shareLayout;
    private View leftBt,rightBt;

    private RecordTextAdapter adapter;
    private ArrayList<ShareItemBean> item;
    private ShareDialog shareDialog;
    private EventCode currentCode = EventCode.TEXT_TRANSLATE;
    private static boolean isNation = false;//是否是民族文字翻译
    /**
     * 页面数据
     */
    private HomeTextModel mDataModel;
    private HdTranslateComponent2 mTranslateComponent;//  文本翻译组件
    private String originalText; //记录输最后请求原文
    private String translatedText;  //记录翻译结果
    private static TranslateRecord translateRecord;

    private ActivityResultLauncher<Intent> activityLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            switch (result.getResultCode()) {
                case Constants.TEXT_HISTORY_RESULT_OK:
                    if (result.getData() != null) {
                        long recordId = result.getData().getLongExtra(Constants.HISTORY_RECORD_ID, -1L);
                        if(recordId != -1L){
                            mDataModel.getRecordById(recordId);
                        }
                    }
                    break;
            }
        }
    });

    //多个open入口
    public static void open(Context context, LimitUseListener listener, TranslateRecord record) {
        setLimitListener(listener);
        translateRecord = record;
        Intent intent = new Intent(context, TextHomeActivity.class);
        context.startActivity(intent);
    }

    public static void open(Context context, LimitUseListener listener, boolean nation) {
        setLimitListener(listener);
        isNation = nation;
        Intent intent = new Intent(context, TextHomeActivity.class);
        context.startActivity(intent);
    }

    public static void open(Context context, LimitUseListener listener) {
        setLimitListener(listener);
        Intent intent = new Intent(context, TextHomeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        TranslationInterior.getTrackerListener().view((isNation?TrackerForTrans.MZYYFY:TrackerForTrans.WBFY) + TrackerForTrans.SY);
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        mTranslateComponent = new HdTranslateComponent2(this);
        getLifecycle().addObserver(mTranslateComponent);
        initView();
        setThemeColor();
        initData();
    }

    private void initData() {
        edit.requestFocus();
        //edit字符监听
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s) && s.length() > 0) {
                    begin.setBackgroundTintList(ColorStateList.valueOf(TranslationInterior.getThemeColor()));
                    clear.setTextColor(TranslationInterior.getThemeColor());
                    clear.setBackgroundTintList(ColorStateList.valueOf(TranslationInterior.getThemeColor()));
                } else {
                    clear.setTextColor(getResources().getColor(R.color.bg_unselect));
                    begin.setBackgroundTintList(null);
                    clear.setBackgroundTintList(null);
                }
                begin.setEnabled(true);
                clear.setEnabled(true);
                edit.setEnabled(true);
                /*if (Constants.TRANSLATE_NORMAL != mDataModel.getTranslateState().getValue()) {
                    mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
                }*/
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        /*
         *  监听页面数据变化(语言改变，翻译状态改变)
         */
        mDataModel.getLanguageFrom().observe(this, huDunLanguage -> {
            if (huDunLanguage != null) {
                fromText.setText(huDunLanguage.getName());
            }
        });
        mDataModel.getLanguageTo().observe(this, huDunLanguage -> {
            if (huDunLanguage != null) {
                toText.setText(huDunLanguage.getName());
            }
        });
        mDataModel.getTranslateState().observe(this, this::translateStateChanged);
        if(isNation){
            mDataModel.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName("中文（简体）"));
            mDataModel.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName("藏语"));
        }else {
            String fromLangName = PreferenceMgr.getInstance().getTranslatePreference().getTansFromLanguage();
            String toLangName = PreferenceMgr.getInstance().getTranslatePreference().getTansToLanguage();
            mDataModel.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName(fromLangName));
            mDataModel.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName(toLangName));
        }
        mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);

        mDataModel.getOperateRecord().observe(this, translateRecord -> {
            if(translateRecord == null){
                return;
            }
            if(translateRecord.getLanguageFrom() != null){
                mDataModel.setLanguageFrom(translateRecord.getLanguageFrom());
            }
            if(translateRecord.getLanguageTo() != null){
                mDataModel.setLanguageTo(translateRecord.getLanguageTo());
            }
            String origContent = translateRecord.getContentOrig();
            edit.setText(origContent);
            if(origContent != null){
                edit.setSelection(origContent.length());
            }
            tvTranslated.setText(translateRecord.getContentTranslate());
            mDataModel.setTranslateState(Constants.TRANSLATED);
            translatedText = translateRecord.getContentTranslate();
        });

        if(translateRecord != null){
            mDataModel.setOperateRecord(translateRecord);
        }
    }

    @Override
    public void onBackPressed() {
        if(translateLayout.getVisibility() == View.VISIBLE){
            clear.performClick();
        }else {
            finish();
        }
    }

    @Override
    protected void onResume() {
        refreshRecords();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDataModel.getTranslateState().removeObservers(this);
        mDataModel.getLanguageFrom().removeObservers(this);
        mDataModel.getLanguageTo().removeObservers(this);
        getLifecycle().removeObserver(mTranslateComponent);
    }

    private boolean hasData = true;

    /**
     * 刷新记录
     */
    private void refreshRecords() {
        Observable.create((ObservableOnSubscribe<List<TranslateRecord>>) emit -> {
            emit.onNext(DataBaseMgr.getInstance().getAllRecords(false,isNation));
            emit.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(new DisposableObserver<List<TranslateRecord>>() {
                    @Override
                    public void onNext(List<TranslateRecord> list) {
                        mDataModel.setListTranslateRecord(list);
                        if (list != null && list.size() > 0) {
                            hasData = true;
                            if (list.size() > 3) {
                                //只获取前3条数据
                                List<TranslateRecord> translateRecords = list.subList(0, 3);

                                adapter.setNewInstance(translateRecords);
                            } else {
                                adapter.setNewInstance(list);
                            }
                        } else {
                            hasData = false;
                            adapter.setNewInstance(null);
                        }
                        if (mDataModel.getTranslateState().getValue() != Constants.TRANSLATED) {
                            mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    /**
     * 清空
     */
    private void clearAll() {
        clearFrom();
        clearTo();
    }

    /**
     * 清空From
     */
    private void clearFrom() {
        edit.setText("");
    }

    /**
     * 清空To
     */
    private void clearTo() {
        tvTranslated.setText("");

    }

    private void initView() {
        back = (ImageView) findViewById(R.id.back);
        fromText = (TextView) findViewById(R.id.tv_from);
        toText = (TextView) findViewById(R.id.tv_to);
        exchange = (ImageView) findViewById(R.id.icon_exchange);
        edit = (EditText) findViewById(R.id.input_edit);
        clear = (TextView) findViewById(R.id.clear_text);
        begin = (TextView) findViewById(R.id.begin);
        historyLayout = (LinearLayout) findViewById(R.id.history_layout);
        moreLayout = (LinearLayout) findViewById(R.id.more_layout);
        moreText = (TextView) findViewById(R.id.more_text);
        moerIcon = (ImageView) findViewById(R.id.more_arrow);
        imgShare = (ImageView) findViewById(R.id.img_share);
        historyRecycler = (RecyclerView) findViewById(R.id.text_recycler);
        contentLayout = (RelativeLayout) findViewById(R.id.result_content);
        translateLayout = (RelativeLayout) findViewById(R.id.result_layout);
        tvTranslated = (TextView) findViewById(R.id.result_text);
        copyLayout = (LinearLayout) findViewById(R.id.copy_layout);
        shareLayout = (LinearLayout) findViewById(R.id.share_layout);
        leftBt = findViewById(R.id.left_bt);
        rightBt = findViewById(R.id.right_bt);

        back.setOnClickListener(this);
        leftBt.setOnClickListener(this);
        rightBt.setOnClickListener(this);
        exchange.setOnClickListener(this);
        clear.setOnClickListener(this);
        begin.setOnClickListener(this);
        moreLayout.setOnClickListener(this);
        copyLayout.setOnClickListener(this);
        shareLayout.setOnClickListener(this);
        mDataModel = new ViewModelProvider(this).get(HomeTextModel.class);
        historyRecycler.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RecordTextAdapter(null);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @SingleItemClick
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                TranslateRecord record = (TranslateRecord) adapter.getData().get(position);
                mDataModel.setOperateRecord(record);
            }
        });
        historyRecycler.setAdapter(adapter);

        item = new ArrayList();
        item.add(new ShareItemBean(R.mipmap.text_icon_share_word, getResources().getString(R.string.export_word)));
        item.add(new ShareItemBean(R.mipmap.text_icon_share_txt, getResources().getString(R.string.export_txt)));
        item.add(new ShareItemBean(R.mipmap.text_icon_share_pdf, getResources().getString(R.string.export_pdf)));

        if(isNation){
            contentLayout.setBackgroundResource(R.drawable.shape_corner_ffffff_x10);
            translateLayout.setBackgroundResource(R.drawable.shape_corner_ffffff_x10);
            imgShare.setImageResource(R.mipmap.icon_text_share2);
        }
    }


    boolean isFromPage = true;

    @Override
    public void onClick(View v) {
        if(XClickUtil.isFastDoubleClick(v,XClickUtil.INTERVAL_MILLIS)){
            return;
        }
        int id = v.getId();
        if (id == R.id.back) {
            onBackPressed();
        } else if (id == R.id.left_bt) {
            isFromPage = true;
            showSelectLanguageDialog();
            mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);

        } else if (id == R.id.right_bt) {
            isFromPage = false;
            showSelectLanguageDialog();
            mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);

        } else if (id == R.id.icon_exchange) { //语种互换
            showTranslateAnimation();

        } else if (id == R.id.clear_text) {     //清空
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WBFY, TrackerForTrans.CLEAR_TEXT);
            clearAll();
            mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
        } else if (id == R.id.begin) {  //开始执行翻译
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WBFY, TrackerForTrans.START_TRANS);
            if (isLimit4Use(isNation?EventCode.TEXT_NATION_TRANSLATE:EventCode.TEXT_TRANSLATE))
                executeTranslate(edit.getText().toString());


        } else if (id == R.id.more_layout) {    //翻译历史
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WBFY, TrackerForTrans.TEXT_TRANS_RECORD);
            Intent intent = new Intent(TextHomeActivity.this, TextHistoryActivity.class);
            intent.putExtra("is_nation",isNation);
            intent.putExtra("title_name",getString(R.string.history_text));
            intent.putExtra("isFromTranslatePage", true);
            if (isLimit4Use(isNation?EventCode.TEXT_NATION_HISTORY:EventCode.TEXT_HISTORY)) {
                activityLauncher.launch(intent);
            }

        } else if (id == R.id.copy_layout) {    //复制
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WBFY, TrackerForTrans.FuZhi);
            if (isLimit4Use(isNation?EventCode.TEXT_NATION_COPY:EventCode.TEXT_COPY)) {
                ClipboardManager cmb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                ClipData mClipData = ClipData.newPlainText("翻译结果", translatedText);
                cmb.setPrimaryClip(mClipData);
                Toast.makeText(this, "结果已复制", Toast.LENGTH_SHORT).show();
            }

        } else if (id == R.id.share_layout) {       //分享
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WBFY, TrackerForTrans.FenXiang);
            if (null != shareDialog) {
                shareDialog.show(getSupportFragmentManager(), "TextHomeActivity");
            } else {
                shareDialog = ShareDialog.builder().setList(item)
                        .setButtonColor(TranslationInterior.getThemeColor())
                        .setItemClickListenner(new ShareDialog.OnShareItemClickListenner() {
                            @Override
                            public void OnItemClick(Dialog dialog, ShareResultAdapter adapter, int position) {
                                if (shareMG == null) {
                                    shareMG = new ShareTextFileManager(getActivity());
                                }
                                switch (position) {
                                    case 0: //导出Word
                                        if (isLimit4Use(EventCode.TEXT_SHARE_WORD)) {
                                            shareWord();
                                        }
                                        break;
                                    case 1://导出TXT
                                        if (isLimit4Use(EventCode.TEXT_SHARE_TXT)) {
                                            shareTxt();
                                        }
                                        break;
                                    case 2://导出PDF
                                        if (isLimit4Use(EventCode.TEXT_SHARE_PDF)) {
                                            sharePdf();
                                        }
                                        break;
                                }
                                dialog.dismiss();
                            }
                        }).build(isNation);
                shareDialog.show(getSupportFragmentManager(), "TextHomeActivity");
            }
        }
    }


    /**
     * 互换语种动画
     */
    private void showTranslateAnimation() {
        if("自动检测".equals(mDataModel.getLanguageFrom().getValue().getName())){
            ToastUtils.showNormal(getResources().getString(R.string.tips_to_not_auto));
            return;
        }
        TranslateAnimation ta1 = new TranslateAnimation(0, leftBt.getWidth() + exchange.getWidth(), 0, 0);
        ta1.setDuration(600);
        ta1.setFillAfter(true);
        leftBt.startAnimation(ta1);
        leftBt.bringToFront();

        TranslateAnimation ta2 = new TranslateAnimation(0, -rightBt.getWidth()-exchange.getWidth(), 0, 0);
        ta2.setDuration(600);
        ta2.setFillAfter(true);
        rightBt.startAnimation(ta2);
        rightBt.bringToFront();

        ta1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                HuDunLanguage fromTemp = mDataModel.getLanguageFrom().getValue();
                mDataModel.setLanguageFrom(mDataModel.getLanguageTo().getValue());
                mDataModel.setLanguageTo(fromTemp);
                mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        ta2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /**
     * 每点击 功能事件 就需要走APP的接口实现
     *
     * @param code 事件码  分别对应各个事件按钮
     * @return true 可以执行该功能   false 拦截。APP端的接口实现 intercept
     */
    private boolean isLimit4Use(EventCode code) {
        return !intercept(code);
    }

    private SimpleDateFormat mFormat;

    public String shareFileName() {
        if (null == mFormat)
            mFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return mFormat.format(new Date().getTime());
    }

    //还未把分享从sdk 抽取出来前的写法。暂时保留。  可自行封装。
    private ShareTextFileManager shareMG;

    private void shareWord() {
        shareMG.shareTextFile(StringUtils.template(originalText, translatedText), shareFileName() + ".doc", EnShareFileType.WORD_FILE);
    }

    private void shareTxt() {
        shareMG.shareTextFile(StringUtils.template(originalText, translatedText), shareFileName(), EnShareFileType.TXT_FILE);
    }

    private void sharePdf() {
        shareMG.shareTextFile(StringUtils.template(originalText, translatedText), shareFileName() + ".pdf", EnShareFileType.PDF_FILE);
    }


    //选择语言弹框
    private void showSelectLanguageDialog() {
        /*SelectLanguageDialog.newInstance(mDataModel.getLanguageFrom().getValue(), mDataModel.getLanguageTo().getValue(), isFromPage, false, isNation)
                .setOnLanguageChangedListener((language, isFrom) -> {
                    if (isFrom) {
                        mDataModel.setLanguageFrom(language);
                    } else {
                        mDataModel.setLanguageTo(language);
                    }
                }).show(getSupportFragmentManager(), "TextHomeActivity");*/

        LanguageDialog dialog = new LanguageDialog(
                Objects.requireNonNull(mDataModel.getLanguageFrom().getValue()),
                Objects.requireNonNull(mDataModel.getLanguageTo().getValue()),
                isFromPage, LanguageDialogType.TEXT, LanguageDialogType.TO_TEXT);
        dialog.show(getSupportFragmentManager(),"LanguageDialog");
        dialog.setOnLanguageChangedListener((fromLanguage, toLanguage, selectedLanguage) -> {
            mDataModel.setLanguageFrom(fromLanguage);
            PreferenceMgr.getInstance().getTranslatePreference().saveTansFromLanguage(fromLanguage.getName());
            mDataModel.setLanguageTo(toLanguage);
            PreferenceMgr.getInstance().getTranslatePreference().saveTansToLanguage(toLanguage.getName());
        });
    }

    //根据app端 保存到TransInit的静态颜色对象，设置颜色。 可另行保存。没有final修饰。有被释放风险
    protected void setThemeColor() {
        moreText.setTextColor(TranslationInterior.getThemeColor());
        moerIcon.setImageTintList(ColorStateList.valueOf(TranslationInterior.getThemeColor()));
    }

    private String lastTransCode;
    private String lastOriginalCode;


    /**
     * 执行翻译  参考项目原有逻辑。
     */
    private void executeTranslate(String origContent) {
        if (TextUtils.isEmpty(origContent))
            return;
        //如果最后请求原文和最后请求目标语言都一致则不请求接口，从历史数据获取并展示
        if (origContent.equals(originalText)) {
            if (mDataModel.getLanguageTo().getValue().getTranslateCode().equals(lastTransCode)
                    && mDataModel.getLanguageFrom().getValue().getTranslateCode().equals(lastOriginalCode)) {
                if (adapter.getData().size() > 0) {
                    TranslateRecord record = adapter.getData().get(0);
                    if (null != record) {
                        mDataModel.setOperateRecord(record);
                        Toast.makeText(TextHomeActivity.this, "已完成对应翻译", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }
        }


        //记录下最后请求的目标语言
        lastTransCode = this.mDataModel.getLanguageTo().getValue().getTranslateCode();
        lastOriginalCode = this.mDataModel.getLanguageFrom().getValue().getTranslateCode();
        showLoadDialog("翻译中...");
        mTranslateComponent.translationText(origContent,
                this.mDataModel.getLanguageFrom().getValue().getTranslateCode(),
                this.mDataModel.getLanguageTo().getValue().getTranslateCode(),
                PreferenceMgr.getInstance().isOpenOfflineTrans(),
                new TranslateCallback() {
                    @Override
                    public void onTranslateFailed(int code, String msg) {
                        originalText = "";
                        hideLoadDialog();
                        TextHomeActivity.this.mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
                        if(code == Constants.ResponseCode.ERROR_IS_DANGER
                                || code == Constants.ResponseCode.ERROR_COMM){
                            ToastUtils.showError(msg);
                        }else {
                            ToastUtils.showError(R.string.fanyi_faith_tip);
                        }
                    }

                    @Override
                    public void onTranslateCompleted(
                            String data,
                            String fromLangCode,
                            String toLangCode,
                            boolean status) {
                        //记录下最后请求的原文
                        originalText = origContent;
                        hideLoadDialog();
                        TextHomeActivity.this.mDataModel.setTranslateState(Constants.TRANSLATED);
                        TranslateRecord record = new TranslateRecord();
                        record.setIsVoice(false);
                        record.setIsNation(isNation);
                        record.setIsCollected(false);
                        record.setLanguageFrom(TextHomeActivity.this.mDataModel.getLanguageFrom().getValue());
                        record.setLanguageTo(TextHomeActivity.this.mDataModel.getLanguageTo().getValue());
                        record.setContentOrig(origContent);
                        record.setContentTranslate(data);
                        record.setTriggerTime(System.currentTimeMillis());
                        //重复数据。就删除前面的历史数据
                        DataBaseMgr instance = DataBaseMgr.getInstance();
                        instance.isContain(record);
                        instance.addTranslateRecord(record);

                        //翻译成功。消耗一次免费试用
                        consumeFreeTrial();
                        //埋点，翻译结果+1
                        TranslationInterior.getTrackerListener().view((isNation?TrackerForTrans.MZYYFY:TrackerForTrans.WBFY) + TrackerForTrans.JG);

                        TextHomeActivity.this.mDataModel.getListTranslateRecord().getValue().add(0, record);
                        TextHomeActivity.this.mDataModel.setOperateRecord(record);
                        refreshRecords();
                    }
                });
    }


    /**
     * 当前状态改变
     */
    private void translateStateChanged(int translateState) {
        switch (translateState) {
            case Constants.TRANSLATE_NORMAL://未翻译
                begin.setEnabled(true);
                clear.setEnabled(true);
                edit.setEnabled(true);
                translateLayout.setVisibility(View.GONE);
                break;

            case Constants.TRANSLATING://翻译中
                begin.setEnabled(false);
                clear.setEnabled(false);
                edit.setEnabled(false);
//                translateLayout.setVisibility(View.GONE);
                //翻译中禁止操作和更改原内容
                break;
            case Constants.TRANSLATED://已翻译
                begin.setEnabled(true);
                edit.setEnabled(true);
                clear.setEnabled(true);
                translateLayout.setVisibility(View.VISIBLE);
                break;
        }
        //无论什么情况下 没有数据历史布局都隐藏，否则就显示
        if (null == adapter || !hasData) {
            historyLayout.setVisibility(View.GONE);
        } else {
            historyLayout.setVisibility(View.VISIBLE);
        }

    }

    @NonNull
    @Override
    public EventCode getPageType() {
        return EventCode.TEXT_TRANSLATE;
    }

 /*Disposable disposable = Single.create(new DefaultSubscribe(
            payAudioEditorHandler,
            Configs.TAG_SDK_AUDIO_COMPRESSION)
    ).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe((success, throwable) -> {
                if (success) {
                }
            });

    private static class DefaultSubscribe implements SingleOnSubscribe<Boolean> {

        private final int mFunctionCode;

        public DefaultSubscribe(IPayAudioEditorHandler payAudioEditorHandler, int functionCode) {
            this.mPayAudioEditorHandler = payAudioEditorHandler;
            mFunctionCode = functionCode;
        }

        @Override
        public void subscribe(@NonNull SingleEmitter<Boolean> emitter) throws Throwable {
            emitter.onSuccess(mPayAudioEditorHandler.enableFunction(mFunctionCode));
        }
    }*/
}